package com.comtime.login;

import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.comtime.greendaodemo.DeviceInfo;
import com.comtime.greendaoutils.DataBaseUtil;
import com.comtime.smartbox.BaseActivity;
import com.comtime.smartbox.MainActivity;
import com.comtime.smartkilimanjaro.R;
import com.comtime.utils.MD5Util;
import com.comtime.utils.MyConfig;
import com.comtime.utils.MySharedPreferences;
import com.comtime.utils.ToastUtils;
import com.comtime.utils.Util;
import com.comtime.view.MyProgressDialog;
import com.comyou.comyouhttp.ComyouHttpCallBack;
import com.comyou.comyouhttp.ComyouHttpClient;
import com.comyou.comyouhttp.ComyouHttpProgram;

public class LoginActivity extends BaseActivity {

    EditText edt_phone, edt_pwd;

    TextView tv_one_result;

    ImageView image_pwd_delete, image_pwd_show;

    Button bt_loging;
    String registPhone;
    String registPwd;
    MySharedPreferences mySharedPreferences;
    public static String Exit = "com.comtime.login.exit";
    DataBaseUtil dataBaseUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        registPhone = intent.getStringExtra("phone");
        registPwd = intent.getStringExtra("pwd");
        setContentView(R.layout.activity_login);
        dataBaseUtil = DataBaseUtil.getInstance(this);
        mySharedPreferences = MySharedPreferences.getInstance(this);
        init();
        registerReceiver(receiver, new IntentFilter(Exit));
        handler.postDelayed(runnable, 500);
    }

    /**
     * 初始化
     */
    void init() {
        edt_phone = (EditText) findViewById(R.id.et_phone);
        edt_pwd = (EditText) findViewById(R.id.et_password);
        edt_phone.addTextChangedListener(mTextWatcher);
        edt_pwd.addTextChangedListener(mTextWatcher);
        tv_one_result = (TextView) findViewById(R.id.tv_wrong_content);
        image_pwd_delete = (ImageView) findViewById(R.id.image_pwd_delete);
        image_pwd_show = (ImageView) findViewById(R.id.image_pwd_show);
        bt_loging = (Button) findViewById(R.id.bt_loging);

        bt_loging.setTextColor(getResources().getColor(R.color.item_white));
        bt_loging.setBackgroundResource(R.drawable.bg_round_stroke_white_5dp);
        if (registPhone != null) {
            edt_phone.setText(registPhone);
            edt_pwd.setText(registPwd);
            edt_pwd.setInputType(InputType.TYPE_CLASS_TEXT
                    | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
    }

    //RZC Add 当重新输入信息，错误提示信息隐藏
    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (tv_one_result.getVisibility() == View.VISIBLE) {
                tv_one_result.setVisibility(View.INVISIBLE);
            }
        }
    };
    BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent intent) {
            // TODO Auto-generated method stub
            if (intent.getAction().equals(Exit)) {
                LoginActivity.this.finish();
            }
        }
    };

    /**
     * login
     *
     * @param v
     */
    public void Login(View v) {

        login();

    }

    /**
     * forget
     *
     * @param v
     */
    public void bt_forget_pwd(View v) {
        Intent intent = new Intent(LoginActivity.this, FindBackActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.enter_right, R.anim.exit_left);
    }

    /**
     * register
     *
     * @param v
     */
    public void bt_register(View v) {
        Intent intent = new Intent(LoginActivity.this, RegistActivity.class);
        startActivity(intent);
        //LoginActivity.this.finish();
        overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
    }

    /**
     * 显示或隐藏密码
     */
    boolean show_pwd_flag = false;//默认隐藏

    public void ShowPwdAction(View v) {
        show_pwd_flag = !show_pwd_flag;
        if (show_pwd_flag) {
            //显示密码
            edt_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            image_pwd_show.setImageResource(R.drawable.icon_show);
        } else {
            //隐藏密码
            edt_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            image_pwd_show.setImageResource(R.drawable.icon_hide);
        }

    }

    /**
     * 一键删除手机
     */
    public void DeletePhoneAction(View v) {
        edt_phone.setText("");

    }

    /**
     * 一键删除密码
     */
    public void DeletePwdAction(View v) {
        edt_pwd.setText("");

    }

    /**
     * login
     */
    String phoneNum = "";
    String pwd = "";

    void login() {

        if (!Util.hasNetwork(LoginActivity.this)) {
            showTextOne(getString(R.string.no_network).toString(), false);
            return;
        }

        if (TextUtils.isEmpty(edt_phone.getText())) {
            showTextOne(getString(R.string.input_phone).toString(), false);
            return;
        }
        if (!Util.isMobileNO(edt_phone.getText().toString())) {
            showTextOne(getString(R.string.phone_format_wrong).toString(),
                    false);
            return;
        }
        if (TextUtils.isEmpty(edt_pwd.getText())) {
            showTextOne(getString(R.string.pwd_hint).toString(), false);
            return;
        }


        //填好信息后开始登录
        phoneNum = edt_phone.getText().toString();
        pwd = edt_pwd.getText().toString();
        if (pwd.length() < 6) {
            showTextOne(getString(R.string.pwd_short).toString(), false);
            return;
        }
        if (pwd.length() > 20) {
            showTextOne(getString(R.string.pwd_more).toString(), false);
            return;
        }

        final MyProgressDialog progressDialog = new MyProgressDialog(
                LoginActivity.this);
        progressDialog.setContent(getText(R.string.login_getting).toString());
        progressDialog.show();
        ComyouHttpProgram httpProgram = new ComyouHttpProgram();
        httpProgram.add("phoneNum", phoneNum);
        httpProgram.add("pwd", MD5Util.md5(pwd));
        ComyouHttpClient httpClient = new ComyouHttpClient(MyConfig.IP
                + "app/Login");

        httpClient.postAsync(httpProgram, new ComyouHttpCallBack() {

            @Override
            public void onResponse(final String resString) {
                progressDialog.dismiss();

                Log.e("tag", "resString ：" + resString);

                /*runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO

                        //ToastUtils.showToast(LoginActivity.this, "登陆成功："+ resString, 3000);
                    }
                });*/
                try {
                    JSONObject jsonObject = new JSONObject(resString);
                    int status = jsonObject.getInt("err");
                    if (status == 0) {
                        JSONObject dataObject = jsonObject
                                .getJSONObject("data");
                        int user_Id = dataObject.getInt("id");

                        dataBaseUtil.deleteDeviceInfoByPhoneNum(phoneNum);
                        JSONArray deviceArray = dataObject
                                .getJSONArray("devices");
                        if (deviceArray != null && deviceArray.length() > 0) {
                            for (int i = 0; i < deviceArray.length(); i++) {

                                JSONObject object = (JSONObject) deviceArray
                                        .opt(i);
                                int deviceID = object.getInt("id");
                                String mac = object.getString("mac");
                                //String master_user_phone=object.getString("master_user_phone");

                                DeviceInfo deviceInfo = new DeviceInfo();
                                deviceInfo.setServer_id(deviceID);
                                deviceInfo.setMac(mac);
                                deviceInfo.setPhoneNum(phoneNum);
                                dataBaseUtil.saveDeviceInfo(deviceInfo);
                            }
                        }
                        mySharedPreferences.saveIsLogined(true);
                        mySharedPreferences.savePhoneNum(phoneNum);
                        mySharedPreferences.saveUserName(phoneNum);
                        mySharedPreferences.savePasswd(pwd);
                        mySharedPreferences.saveBluAdress("");
                        mySharedPreferences.saveUserId(user_Id);

                        //TODO:判断授权信息
                        JSONArray authArray = dataObject.getJSONArray("my_device_result");
                        /*if(authArray !=null){
                            //拿到授权信息,存入到AuthInfo
                            mySharedPreferences.savaBoolen("needAuth",true);

                        }else {
                            mySharedPreferences.savaBoolen("needAuth",false);
                        }*/
                        mySharedPreferences.savaBoolen("needAuth",false);
                        //TODO:判断授权信息
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                    } else if (status == 2) {

                        showTextOne(
                                getText(R.string.phone_pwd_fail).toString(),
                                false);


                    } else {
                        showTextOne(getText(R.string.login_fail).toString(),
                                false);
                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(String arg0, IOException arg1) {
                progressDialog.dismiss();
                showToast(getString(R.string.login_fail).toString());
            }

        });
    }

    Handler handler = new Handler();

    Runnable runnable = new Runnable() {

        @Override
        public void run() {

            if (!TextUtils.isEmpty(edt_pwd.getText())) {
                image_pwd_delete.setVisibility(View.VISIBLE);
            } else {
                image_pwd_delete.setVisibility(View.INVISIBLE);
            }
            //RZC 8-24 随时可以让用户点击登录，然后弹出提示
            /*if (edt_phone.getText().toString().length() == 11 && edt_pwd.getText().toString().length() >= 6) {
                bt_loging.setEnabled(true);
                bt_loging.setTextColor(getResources().getColor(R.color.item_white));
                bt_loging.setBackgroundResource(R.drawable.bg_round_stroke_white_5dp);
            } else {
                bt_loging.setEnabled(false);
                bt_loging.setTextColor(getResources().getColor(R.color.item_gray));
                bt_loging.setBackgroundResource(R.drawable.bg_round_stroke_gray_5dp);
            }*/
            handler.postDelayed(runnable, 500);
        }
    };
    /**
     * 自定义提示语
     *
     * @param str
     */
    Toast toast = null;

    void showToast(String str) {
        if (toast != null) {
            toast.cancel();
        }
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.toastshow, null);
        TextView textView = (TextView) view.findViewById(R.id.toastshow);
        textView.setText(str);
        Toast toast = new Toast(this);
        double d = getResources().getDisplayMetrics().density;
        toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.CENTER, 0, 0);
        //toast.setDuration(1500);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(view);
        toast.show();
    }

    void showTextOne(String str, boolean erroy) {
        tv_one_result.setVisibility(View.VISIBLE);
        tv_one_result.setText(str);
        if (erroy) {
            tv_one_result.setTextColor(getResources().getColor(
                    R.color.item_white));
        } else {
            tv_one_result.setTextColor(getResources().getColor(
                    R.color.item_orange));
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        Log.e("registPhone", "" + registPhone);
        if (registPhone == null) {
            edt_phone.setText(mySharedPreferences.getPhoneNum());
            edt_pwd.setText(mySharedPreferences.getPasswd());
        }

    }
}
